package com.pool.store;

import java.util.List;

import org.apache.http.HttpResponse;

import com.pool.auth.Auth;
import com.pool.net.SpreadsheetsConnector;
import com.pool.store.gdata.GDataFactory;

/**
 * Abstract class for Spreadsheets {@link Store}s.
 * 
 * @author claveld@gmail.com (David Clavel)
 */
public class AbstractSpreadsheetsStore<E> {
  
  private static final int OK = 200;
  private static final int CREATED = 201;
  
  private final Auth auth;
  private final SpreadsheetsConnector connector;
  
  public AbstractSpreadsheetsStore(Auth auth, SpreadsheetsConnector connector) {
    this.auth = auth;
    this.connector = connector;
  }
  
  protected boolean sendCreateRequest(String url, String xml) {
    checkUserIsLoggedIn();
    HttpResponse response = connector.doPost(auth.getAuthKey(), url, xml);
    return response != null && response.getStatusLine().getStatusCode() == CREATED;
  }

  protected boolean sendRetrieveRequest(String url, GDataFactory<E> elementsFactory, List<E> elements) {
    checkUserIsLoggedIn();
    XmlResponseProcessor<E> xmlProcessor = new XmlResponseProcessor<E>(elementsFactory);
    HttpResponse response = connector.doGet(auth.getAuthKey(), url);
    if (response == null) {
      // TODO(claveld): Log something.
      return false;
    } else if (response.getStatusLine().getStatusCode() != OK) {
      // TODO(claveld): Log something.
      return false;
    }
    
    // At this point, the response is OK.    
    xmlProcessor.process(response);
    elements.addAll(xmlProcessor.getList());
    return true;
  }
  
  private void checkUserIsLoggedIn() {
    if (!auth.isAlreadyLogged()) {
      throw new UnsupportedOperationException("User is not logged in.");
    }
  }
}
